package com.qf.quduba.controller;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @author 17312
 * @time2020/9/1020:23
 */
@Controller
@CrossOrigin
@RequestMapping("/file")
public class FileUpoadController {

    @ResponseBody
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String upload(MultipartFile file){
        //将文件保存到linux（FTP协议）
        String originalFilename = file.getOriginalFilename();
        String s = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = System.currentTimeMillis()+s;

        try {
            FTPClient ftpClient = new FTPClient();
            ftpClient.connect("39.99.161.217",21);
            boolean state = ftpClient.login("root", "YINjun940403");
            int replyCode = ftpClient.getReplyCode();

            //如果响应码在200到299之间，表示与FTP站点的连接是成功的
            if(FTPReply.isPositiveCompletion(replyCode)){
                //设置编码UTF-8
                ftpClient.setControlEncoding("UTF-8");
                //设置被动模式（腾讯云必须添加，其他云待测试）
                //ftpClient.enterLocalPassiveMode();

                //a.设置接收文件类型为二进制文件
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                //b.在服务器上创建images文件夹
                //ftpClient.makeDirectory("images");
                //c.切换进入到images文件夹
                ftpClient.changeWorkingDirectory("/usr/local/webserver/nginx/pro_name/imgs");
                //d.将文件上传到ftp服务器
                InputStream inputStream = file.getInputStream();
                boolean b = ftpClient.storeFile(fileName, inputStream);

                inputStream.close();
                //2.退出登录
                ftpClient.logout();
                return "http://39.99.161.217/imgs/"+fileName;
            }else{
                return "fail";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }


}
